package com.example.springdataes.test;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;

import java.io.IOException;
import java.util.Arrays;
import java.util.Map;

public class ESTest_Client {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(RestClient.builder(
                new HttpHost("localhost",9200,"http") //scheme默认是"http"
//                        new HttpHost("192.168.1.13",9200,"http") // 配置多个节点
        ));

        // createIdex
//        CreateIndexRequest createIndexRequest = new CreateIndexRequest("user");
//        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
//        boolean acknowledged = createIndexResponse.isAcknowledged();
//        System.out.println("索引操作："+acknowledged);

        // 检索索引
//        GetIndexRequest getIndexRequest = new GetIndexRequest("user");
//        GetIndexResponse getIndexResponse = restHighLevelClient.indices().get(getIndexRequest, RequestOptions.DEFAULT);
//        System.out.println(getIndexResponse.getAliases());
//        System.out.println(getIndexResponse.getMappings());
//        System.out.println(Arrays.toString(getIndexResponse.getIndices()));

        // 删除索引
//        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("user");
//        AcknowledgedResponse delete = restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
//        boolean acknowledged = delete.isAcknowledged();
//        System.out.println("delete acknowledged:"+acknowledged);

        // 新增文档 - 请求对象
//        IndexRequest request = new IndexRequest();
//        // 设置索引及唯一性标识
//        request.index("user").id("1001");
//        // 创建数据对象
//        MyUser user = new MyUser();
//        user.setName("zhangsan");
//        user.setAge(30);
//        user.setSex("男");
//        ObjectMapper objectMapper = new ObjectMapper();
//        String productJson = objectMapper.writeValueAsString(user);
//        // 添加文档数据，数据格式为 JSON 格式
//        request.source(productJson, XContentType.JSON);
//        // 客户端发送请求，获取响应对象
//        IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
//        ////3.打印结果信息
//        System.out.println("_index:" + response.getIndex());
//        System.out.println("_id:" + response.getId());
//        System.out.println("_result:" + response.getResult());

        // 修改文档 - 请求对象
//        UpdateRequest request = new UpdateRequest();
//        // 配置修改参数
//        request.index("user").id("1001");
//        // 设置请求体，对数据进行修改
//        request.doc(XContentType.JSON, "sex", "女");
//        // 客户端发送请求，获取响应对象
//        UpdateResponse response = restHighLevelClient.update(request, RequestOptions.DEFAULT);
//        System.out.println("_index:" + response.getIndex());
//        System.out.println("_id:" + response.getId());
//        System.out.println("_result:" + response.getResult());

        // 查询文档
//        //1.创建请求对象
//        GetRequest request = new GetRequest().index("user").id("1001");
//        //2.客户端发送请求，获取响应对象
//        GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);
//        ////3.打印结果信息
//        System.out.println("_index:" + response.getIndex());
//        System.out.println("_type:" + response.getType());
//        System.out.println("_id:" + response.getId());
//        System.out.println("source:" + response.getSourceAsString());

        // 删除文档
//        //创建请求对象
//        DeleteRequest request = new DeleteRequest().index("user").id("1");
//        //客户端发送请求，获取响应对象
//        DeleteResponse response = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
//        //打印信息
//        System.out.println(response.toString());

        //批量新增
//        BulkRequest request = new BulkRequest();
//        request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON, "name", "zhangsan","age",30,"sex","男"));
//        request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name", "lisisi","age",31,"sex","女"));
//        request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON, "name", "wangwu","age",32,"sex","男"));
//        //客户端发送请求，获取响应对象
//        BulkResponse responses = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
//        //打印结果信息
//        System.out.println("took:" + responses.getTook());
//        System.out.println("items:" + Arrays.toString(responses.getItems()));

        //批量删除
//        BulkRequest request = new BulkRequest();
//        request.add(new DeleteRequest().index("user").id("1001"));
//        request.add(new DeleteRequest().index("user").id("1002"));
//        request.add(new DeleteRequest().index("user").id("1003"));
//        //客户端发送请求，获取响应对象
//        BulkResponse responses = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
//        //打印结果信息
//        System.out.println("took:" + responses.getTook());
//        System.out.println("items:" + Arrays.toString(responses.getItems()));

        // 全量检索
//        SearchRequest request = new SearchRequest();
//        request.indices("user");
//        // 构建查询的请求体
//        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//        // 查询所有数据
//        sourceBuilder.query(QueryBuilders.matchAllQuery());
//        request.source(sourceBuilder);
//        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
//        // 查询匹配
//        SearchHits hits = response.getHits();
//        System.out.println("took:" + response.getTook());
//        System.out.println("timeout:" + response.isTimedOut());
//        System.out.println("total:" + hits.getTotalHits());
//        System.out.println("MaxScore:" + hits.getMaxScore());
//        System.out.println("hits========>>");
//        for (SearchHit hit : hits) {
//        //输出每条查询的结果信息
//            System.out.println(hit.getSourceAsString());
//        }
//        System.out.println("<<========");

        // 条件查询
//        // 创建搜索请求对象（term 查询，查询条件为关键字）
//        SearchRequest request = new SearchRequest();
//        request.indices("user");
//        // 构建查询的请求体
//        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//        sourceBuilder.query(QueryBuilders.termQuery("age", "30"));
//        request.source(sourceBuilder);
//        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
//        // 查询匹配
//        SearchHits hits = response.getHits();
//        System.out.println("took:" + response.getTook());
//        System.out.println("timeout:" + response.isTimedOut());
//        System.out.println("total:" + hits.getTotalHits());
//        System.out.println("MaxScore:" + hits.getMaxScore());
//        System.out.println("hits========>>");
//        for (SearchHit hit : hits) {
//        //输出每条查询的结果信息
//            System.out.println(hit.getSourceAsString());
//        }
//        System.out.println("<<========");

        // 分页查询
//        // 创建搜索请求对象
//        SearchRequest request = new SearchRequest();
//        request.indices("user");
//        // 构建查询的请求体
//        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//        sourceBuilder.query(QueryBuilders.matchAllQuery());
//        // 当前页其实索引(第一条数据的顺序号)，from
//        sourceBuilder.from(0);
//        // 每页显示多少条 size
//        sourceBuilder.size(2);
//        request.source(sourceBuilder);
//        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
//        // 查询匹配
//        SearchHits hits = response.getHits();
//        System.out.println("took:" + response.getTook());
//        System.out.println("timeout:" + response.isTimedOut());
//        System.out.println("total:" + hits.getTotalHits());
//        System.out.println("MaxScore:" + hits.getMaxScore());
//        System.out.println("hits========>>");
//        for (SearchHit hit : hits) {
//        //输出每条查询的结果信息
//            System.out.println(hit.getSourceAsString());
//        }
//        System.out.println("<<========");

        // 数据排序
//        SearchRequest request = new SearchRequest();
//        request.indices("user");
//        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//        sourceBuilder.query(QueryBuilders.matchAllQuery());
//        // 排序
//        sourceBuilder.sort("age", SortOrder.ASC);
//        request.source(sourceBuilder);
//        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
//        // 查询匹配
//        SearchHits hits = response.getHits();
//        System.out.println("took:" + response.getTook());
//        System.out.println("timeout:" + response.isTimedOut());
//        System.out.println("total:" + hits.getTotalHits());
//        System.out.println("MaxScore:" + hits.getMaxScore());
//        System.out.println("hits========>>");
//        for (SearchHit hit : hits) {
//        //输出每条查询的结果信息
//            System.out.println(hit.getSourceAsString());
//        }
//        System.out.println("<<========");


        // 过滤字段
//        // 基于字段排序
//        SearchRequest request = new SearchRequest();
//        request.indices("user");
//        // 构建查询的请求体
//        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//        sourceBuilder.query(QueryBuilders.matchAllQuery());
//        //查询字段过滤
//        String[] excludes = {};
//        String[] includes = {"name", "age"};
//        sourceBuilder.fetchSource(includes, excludes);
//        request.source(sourceBuilder);
//        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
//        // 查询匹配
//        SearchHits hits = response.getHits();
//        System.out.println("took:" + response.getTook());
//        System.out.println("timeout:" + response.isTimedOut());
//        System.out.println("total:" + hits.getTotalHits());
//        System.out.println("MaxScore:" + hits.getMaxScore());
//        System.out.println("hits========>>");
//        for (SearchHit hit : hits) {
//        //输出每条查询的结果信息
//            System.out.println(hit.getSourceAsString());
//        }
//        System.out.println("<<========");


        // 组合查询
//        // 使用bool完成组合查询
//        SearchRequest request = new SearchRequest();
//        request.indices("user");
//        // 构建查询的请求体
//        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//        // 必须包含
//        boolQueryBuilder.must(QueryBuilders.matchQuery("age", "30"));
//        // 一定不含
//        boolQueryBuilder.mustNot(QueryBuilders.matchQuery("name", "wamgwu"));
//        // 可能包含
//        // 或的意思，上面写的是must，所以这里条件无用。如果想表示或的关系，需要将上面的must改为should
//        boolQueryBuilder.should(QueryBuilders.matchQuery("sex", "女"));
//        sourceBuilder.query(boolQueryBuilder);
//        request.source(sourceBuilder);
//        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
//        // 查询匹配
//        SearchHits hits = response.getHits();
//        System.out.println("took:" + response.getTook());
//        System.out.println("timeout:" + response.isTimedOut());
//        System.out.println("total:" + hits.getTotalHits());
//        System.out.println("MaxScore:" + hits.getMaxScore());
//        System.out.println("hits========>>");
//        for (SearchHit hit : hits) {
//        //输出每条查询的结果信息
//            System.out.println(hit.getSourceAsString());
//        }
//        System.out.println("<<========");


        // 范围查询
//        SearchRequest request = new SearchRequest();
//        request.indices("user");
//        // 构建查询的请求体
//        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age");
//        // 大于等于
//        rangeQuery.gte("30");
//        // 小于等于
//        rangeQuery.lte("40");
//        sourceBuilder.query(rangeQuery);
//        request.source(sourceBuilder);
//        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
//        // 查询匹配
//        SearchHits hits = response.getHits();
//        System.out.println("took:" + response.getTook());
//        System.out.println("timeout:" + response.isTimedOut());
//        System.out.println("total:" + hits.getTotalHits());
//        System.out.println("MaxScore:" + hits.getMaxScore());
//        System.out.println("hits========>>");
//        for (SearchHit hit : hits) {
//        //输出每条查询的结果信息
//            System.out.println(hit.getSourceAsString());
//        }
//        System.out.println("<<========");


        // 模糊查询
//        SearchRequest request = new SearchRequest();
//        request.indices("user");
//        // 构建查询的请求体
//        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//        // Fuzziness.ONE 结果前后相差一个字符也能检索出来
//        sourceBuilder.query(QueryBuilders.fuzzyQuery("name","zhangsan").fuzziness(Fuzziness.ONE));
//        request.source(sourceBuilder);
//        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
//        // 查询匹配
//        SearchHits hits = response.getHits();
//        System.out.println("took:" + response.getTook());
//        System.out.println("timeout:" + response.isTimedOut());
//        System.out.println("total:" + hits.getTotalHits());
//        System.out.println("MaxScore:" + hits.getMaxScore());
//        System.out.println("hits========>>");
//        for (SearchHit hit : hits) {
//        //输出每条查询的结果信息
//            System.out.println(hit.getSourceAsString());
//        }
//        System.out.println("<<========");


        // 高亮查询
//        SearchRequest request = new SearchRequest().indices("user");
//        //2.创建查询请求体构建器
//        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//        //构建查询方式：高亮查询
//        TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("name","zhangsan");
//        //设置查询方式
//        sourceBuilder.query(termsQueryBuilder);
//        //构建高亮字段
//        HighlightBuilder highlightBuilder = new HighlightBuilder();
//        highlightBuilder.preTags("<font color='red'>");//设置标签前缀
//        highlightBuilder.postTags("</font>");//设置标签后缀
//        highlightBuilder.field("name");//设置高亮字段
//        //设置高亮构建对象
//        sourceBuilder.highlighter(highlightBuilder);
//        //设置请求体
//        request.source(sourceBuilder);
//        //3.客户端发送请求，获取响应对象
//        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
//        //4.打印响应结果
//        SearchHits hits = response.getHits();
//        System.out.println("took::"+response.getTook());
//        System.out.println("time_out::"+response.isTimedOut());
//        System.out.println("total::"+hits.getTotalHits());
//        System.out.println("max_score::"+hits.getMaxScore());
//        System.out.println("hits::::>>");
//        for (SearchHit hit : hits) {
//            String sourceAsString = hit.getSourceAsString();
//            System.out.println(sourceAsString);
//            //打印高亮结果
//            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
//            System.out.println(highlightFields);
//        }
//        System.out.println("<<::::");


        // 聚合查询
//        SearchRequest request = new SearchRequest().indices("user");
//        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//        sourceBuilder.aggregation(AggregationBuilders.max("maxAge").field("age"));
//        //设置请求体
//        request.source(sourceBuilder);
//        //3.客户端发送请求，获取响应对象
//        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
//        //4.打印响应结果
//        System.out.println(JSON.toJSONString(response.getAggregations()));
//        System.out.println("hits========>>");
//        for (SearchHit hit : hits) {
//        //输出每条查询的结果信息
//            System.out.println(hit.getSourceAsString());
//        }
//        System.out.println("<<========");


        // 分组查询
//        SearchRequest request = new SearchRequest().indices("user");
//        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//        sourceBuilder.aggregation(AggregationBuilders.terms("age_groupby").field("age"));
//        //设置请求体
//        request.source(sourceBuilder);
//        //3.客户端发送请求，获取响应对象
//        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
//        //4.打印响应结果
//        SearchHits hits = response.getHits();
//        System.out.println(response.getAggregations());
//        System.out.println("hits========>>");
//        for (SearchHit hit : hits) {
//        //输出每条查询的结果信息
//            System.out.println(hit.getSourceAsString());
//        }
//        System.out.println("<<========");


        restHighLevelClient.close();
    }
}
